{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}RBAC权限管理系统{% endblock %}</title>
    {% load static %}
    <!-- Bootstrap CSS -->
    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
    <!-- FontAwesome 图标 -->
    <link rel="stylesheet" href="{% static 'css/css/all.min.css' %}">
    <style>
        /* 顶部导航栏美化 - 使用清新的现代色调 */
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
            padding-top: 0.3rem;
            padding-bottom: 0.3rem;
            min-height: 60px;
        }
        
        .navbar-brand {
            font-weight: 600;
            font-size: 1.4rem;
            color: #fff !important;
        }
        
        .navbar-nav .nav-link {
            font-weight: 500;
            transition: all 0.3s;
            border-radius: 8px;
            margin: 0 5px;
            color: rgba(255, 255, 255, 0.9) !important;
            position: relative;
            overflow: hidden;
            padding: 0.4rem 1rem;
        }
        
        .navbar-nav .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff !important;
            transform: translateY(-2px);
        }
        
        .navbar-nav .nav-link.active {
            background-color: rgba(255, 255, 255, 0.3);
            color: #fff !important;
        }
        
        .navbar-nav .dropdown-menu {
            border-radius: 12px;
            box-shadow: 0 0.5rem 1.5rem rgba(0, 0, 0, 0.15);
            border: none;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            margin-top: 0.3rem;
        }
        
        .navbar-nav .dropdown-item {
            border-radius: 6px;
            margin: 2px 5px;
            transition: all 0.2s;
            padding: 0.5rem 1rem;
        }
        
        .navbar-nav .dropdown-item:hover {
            background-color: #e9ecef;
            transform: translateX(5px);
        }
        
        .navbar-text {
            font-weight: 500;
            display: flex;
            align-items: center;
            color: #fff !important;
        }
        
        /* 侧边栏美化 - 使用清新的现代色调 */
        .sidebar {
            position: fixed;
            top: 60px; /* 与导航栏高度完全匹配 */
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 10px 0; /* 进一步减少内边距 */
            box-shadow: 3px 0 15px rgba(0, 0, 0, 0.08);
            background: linear-gradient(135deg, #f0f8ff 0%, #f5fffa 100%);
            overflow-y: auto;
            width: 200px; /* 从250px缩小到200px */
            transition: all 0.3s ease;
            margin: 0; /* 移除所有外边距 */
        }
        
        .sidebar:hover {
            box-shadow: 5px 0 20px rgba(0, 0, 0, 0.12);
        }
        
        .sidebar .nav-link {
            font-weight: 500;
            color: #4a5568;
            padding: 10px 15px; /* 减少左右内边距 */
            margin: 2px 8px; /* 减少左右外边距 */
            border-radius: 10px;
            transition: all 0.3s;
            display: flex;
            align-items: center;
        }
        
        .sidebar .nav-link:hover {
            color: #2b6cb0;
            background-color: rgba(102, 126, 234, 0.15);
            transform: translateX(5px);
        }
        
        .sidebar .nav-link.active {
            color: #fff;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 10px rgba(102, 126, 234, 0.3);
        }
        
        .sidebar .nav-link i {
            width: 20px; /* 减少图标宽度 */
            text-align: center;
            margin-right: 10px; /* 减少右边距 */
            font-size: 1.1em;
        }
        
        .sidebar .nav.flex-column > .nav-item {
            margin-bottom: 2px; /* 进一步减少底部间距 */
        }
        
        .sidebar .nav.flex-column .nav.flex-column {
            padding-left: 20px; /* 减少子菜单左边距 */
        }
        
        .sidebar .nav.flex-column .nav.flex-column .nav-link {
            font-size: 0.9rem;
            padding: 8px 12px; /* 减少子菜单项内边距 */
        }
        
        /* 主内容区域 */
        main {
            padding-top: 20px;
            margin-top: 60px; /* 与顶部导航栏高度一致 */
            margin-left: 200px; /* 与侧边栏宽度保持一致 */
            transition: all 0.3s ease;
        }
        
        /* 解决内容被顶部导航遮挡的问题 */
        .content-wrapper {
            padding-top: 20px;
        }
        
        /* 响应式调整 */
        @media (max-width: 767.98px) {
            .sidebar {
                top: 60px;
                position: relative;
                height: auto;
                padding: 10px 0;
                width: 100%;
            }
            
            main {
                margin-top: 0;
                margin-left: 0;
            }
        }
        
        /* 面包屑导航 */
        .breadcrumb {
            background-color: #f8f9fa;
            border-radius: 0.5rem;
        }
        
        /* 卡片美化 */
        .card {
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            border: none;
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }
        
        .card:hover {
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
            transform: translateY(-3px);
        }
        
        .card-header {
            border-radius: 15px 15px 0 0 !important;
            background: linear-gradient(135deg, #f0f8ff 0%, #e6f7ff 100%);
            border: none;
            font-weight: 600;
        }
        
        /* 按钮美化 */
        .btn {
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
        }
        
        /* 表格美化 */
        .table {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            border-radius: 10px;
            overflow: hidden;
        }
        
        .table thead th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            font-weight: 600;
            border: none;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(102, 126, 234, 0.08);
        }
        
        /* Dashboard统计卡片样式 */
        .border-left-primary {
            border-left: 0.25rem solid #667eea !important;
        }
        
        .border-left-success {
            border-left: 0.25rem solid #28a745 !important;
        }
        
        .border-left-info {
            border-left: 0.25rem solid #17a2b8 !important;
        }
        
        .border-left-warning {
            border-left: 0.25rem solid #ffc107 !important;
        }
        
        .text-xs {
            font-size: 0.75rem;
        }
        
        .text-gray-800 {
            color: #5a5c69 !important;
        }
        
        .text-gray-300 {
            color: #dddfeb !important;
        }
        
        .shadow {
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15) !important;
        }
        
        .h-100 {
            height: 100%;
        }
        
        .py-2 {
            padding-top: 0.5rem !important;
            padding-bottom: 0.5rem !important;
        }
        
        /* 应用分组菜单样式 */
        .app-group {
            margin-bottom: 1rem;
        }
        
        .app-header {
            padding: 0.5rem 1rem;
            font-weight: bold;
            color: #4a5568;
            border-bottom: 1px solid #e2e8f0;
            margin-bottom: 0.5rem;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .app-header i:first-child {
            margin-right: 0.5rem;
        }
        
        .app-header .toggle-icon {
            transition: transform 0.3s ease;
        }
        
        .app-header.collapsed .toggle-icon {
            transform: rotate(-90deg);
        }
        
        /* 子菜单折叠样式 */
        .menu-item {
            position: relative;
        }
        
        .menu-toggle {
            float: right;
            cursor: pointer;
            transition: transform 0.3s ease;
            font-size: 0.8rem;
            line-height: 1.5;
            padding: 0 5px;
        }
        
        .menu-toggle.collapsed {
            transform: rotate(-90deg);
        }
        
        .sub-menu.collapse:not(.show) {
            display: none;
        }
        
        .sub-menu.collapsing {
            height: 0;
            transition: height 0.3s ease;
        }
        
        /* 菜单项样式调整 */
        .nav-link {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .nav-link .menu-text {
            flex: 1;
        }
        
        .nav-link .menu-icon {
            margin-right: 10px;
        }
        
        /* 优化折叠动画，减少跳动 */
        .sub-menu {
            transition: all 0.3s ease;
        }
        
        /* 为子菜单添加最小高度，减少跳动 */
        .nav.flex-column .nav.flex-column {
            min-height: 0;
        }
        
        /* 为菜单项添加过渡效果 */
        .nav.flex-column .nav-item {
            transition: all 0.2s ease;
        }
    </style>
    {% block extra_css %}{% endblock %}
</head>
<body>
    {% load form_extras %}
    {% load menu_extras %}
    
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light shadow-sm fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="{% url 'accounts:welcome' %}">
                <i class="fas fa-user-shield me-2"></i> RBAC权限管理系统
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link {% if request.resolver_match.url_name == 'welcome' %}active{% endif %}" href="{% url 'accounts:welcome' %}">
                            <i class="fas fa-home me-1"></i> 首页
                        </a>
                    </li>
                </ul>
                
                <ul class="navbar-nav">
                    {% if user.is_authenticated %}
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-user-circle me-1"></i>{{ user.username }}
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="{% url 'accounts:profile' %}"><i class="fas fa-user me-2"></i>个人资料</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="{% url 'accounts:logout' %}"><i class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
                            </ul>
                        </li>
                    {% else %}
                        <li class="nav-item">
                            <a class="nav-link" href="{% url 'accounts:login' %}"><i class="fas fa-sign-in-alt me-1"></i>登录</a>
                        </li>
                    {% endif %}
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            {% if user.is_authenticated %}
            <!-- 侧边栏 -->
            <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-0">
                    <!-- 按应用分组显示菜单 -->
                    {% group_menus_by_app user.get_user_menus as grouped_menus %}
                    {% for app_name, menus in grouped_menus.items %}
                    <div class="app-group" data-app="{{ app_name }}">
                        <div class="app-header">
                            <div>
                                <i class="fas fa-folder"></i>
                                {% get_app_display_name app_name %}
                            </div>
                            <i class="fas fa-chevron-down toggle-icon"></i>
                        </div>
                        <div class="app-menu collapse">
                            <ul class="nav flex-column">
                                {% for menu_item in menus %}
                                    {% with menu=menu_item.menu sub_menus=menu_item.sub_menus %}
                                    {% if menu.is_active %}
                                    <li class="nav-item menu-item">
                                        <a class="nav-link {% if menu.url == request.resolver_match.app_name|add:':'|add:request.resolver_match.url_name %}active{% endif %}" 
                                           href="{% if menu.url %}{% url menu.url %}{% else %}#{% endif %}">
                                            {% if menu.icon %}
                                                <i class="{{ menu.icon }} menu-icon"></i>
                                            {% endif %}
                                            <span class="menu-text">{{ menu.name }}</span>
                                            {% if sub_menus %}
                                                <i class="fas fa-chevron-down menu-toggle"></i>
                                            {% endif %}
                                        </a>
                                        
                                        <!-- 子菜单 -->
                                        {% if sub_menus %}
                                        <div class="sub-menu collapse" id="sub-menu-{{ menu.id }}">
                                            <ul class="nav flex-column ms-3">
                                                {% for sub_menu in sub_menus %}
                                                    {% if sub_menu.is_active %}
                                                    <li class="nav-item">
                                                        <a class="nav-link {% if sub_menu.url == request.resolver_match.app_name|add:':'|add:request.resolver_match.url_name %}active{% endif %}" 
                                                           href="{% if sub_menu.url %}{% url sub_menu.url %}{% else %}#{% endif %}">
                                                            {% if sub_menu.icon %}
                                                                <i class="{{ sub_menu.icon }} menu-icon"></i>
                                                            {% endif %}
                                                            <span class="menu-text">{{ sub_menu.name }}</span>
                                                        </a>
                                                    </li>
                                                    {% endif %}
                                                {% endfor %}
                                            </ul>
                                        </div>
                                        {% endif %}
                                    </li>
                                    {% endif %}
                                    {% endwith %}
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                    {% empty %}
                    <!-- 如果没有分组菜单，显示默认菜单 -->
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link {% if request.resolver_match.url_name == 'dashboard' %}active{% endif %}" href="{% url 'accounts:dashboard' %}">
                                <i class="fas fa-tachometer-alt me-2"></i> 控制台
                            </a>
                        </li>
                    </ul>
                    {% endfor %}
                </div>
            </nav>
            {% endif %}
            
            <!-- 主内容区域 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="content-wrapper">
                    {% if messages %}
                        {% for message in messages %}
                            <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                                {{ message }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        {% endfor %}
                    {% endif %}

                    {% block content %}
                    {% endblock %}
                </div>
            </main>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script>
    <script>
        // 处理应用菜单和子菜单的折叠/展开
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化菜单事件
            initMenuEvents();
            
            // 页面加载时，只展开当前激活菜单的路径，不强制展开所有菜单
            const activeLink = document.querySelector('.nav-link.active');
            if (activeLink) {
                // 展开当前激活链接所在的完整路径
                expandActivePath(activeLink);
            }
            
            // 处理浏览器的前进后退按钮
            window.addEventListener('popstate', function(e) {
                loadContent(window.location.href);
            });
            
            // 展开当前激活菜单的完整路径函数
            function expandActivePath(activeLink) {
                // 1. 展开应用组（如果尚未展开）
                const appGroup = activeLink.closest('.app-group');
                if (appGroup) {
                    const appMenu = appGroup.querySelector('.app-menu');
                    const appHeader = appGroup.querySelector('.app-header');
                    
                    if (appMenu && appHeader) {
                        // 只有在应用组折叠时才展开它
                        if (appHeader.classList.contains('collapsed') || !appMenu.classList.contains('show')) {
                            // 移除collapsed类以确保展开
                            appHeader.classList.remove('collapsed');
                            appMenu.classList.add('show');
                        }
                    }
                    
                    // 2. 展开所有父级菜单（如果尚未展开）
                    let parentElement = activeLink.closest('.nav-item').parentElement;
                    while (parentElement && parentElement.classList.contains('sub-menu')) {
                        const parentMenuItem = parentElement.closest('.nav-item');
                        if (parentMenuItem) {
                            // 展开父级菜单
                            const parentSubMenu = parentElement;
                            const parentToggle = parentMenuItem.querySelector('.menu-toggle');
                            
                            if (parentSubMenu && parentToggle) {
                                // 只有在子菜单折叠时才展开它
                                if (parentToggle.classList.contains('collapsed') || !parentSubMenu.classList.contains('show')) {
                                    // 移除collapsed类
                                    parentToggle.classList.remove('collapsed');
                                    parentSubMenu.classList.add('show');
                                }
                            }
                        }
                        parentElement = parentElement.parentElement;
                    }
                }
            }
            
            // 初始化菜单事件函数
            function initMenuEvents() {
                // 为每个应用标题添加点击事件
                const appHeaders = document.querySelectorAll('.app-header');
                appHeaders.forEach(header => {
                    header.addEventListener('click', function(e) {
                        // 阻止事件冒泡
                        e.stopPropagation();
                        
                        const appMenu = this.nextElementSibling; // 获取下一个兄弟元素，即app-menu
                        
                        // 切换折叠状态
                        this.classList.toggle('collapsed');
                        appMenu.classList.toggle('show');
                    });
                });
                
                // 为每个菜单项的切换按钮添加点击事件
                const menuToggles = document.querySelectorAll('.menu-toggle');
                menuToggles.forEach(toggle => {
                    toggle.addEventListener('click', function(e) {
                        e.preventDefault(); // 阻止默认行为
                        e.stopPropagation(); // 阻止事件冒泡
                        
                        // 获取对应的子菜单
                        const subMenu = this.closest('.nav-item').querySelector('.sub-menu');
                        
                        if (subMenu) {
                            // 切换折叠状态
                            this.classList.toggle('collapsed');
                            subMenu.classList.toggle('show');
                        }
                    });
                });
                
                // 为所有菜单链接添加Ajax处理
                const menuLinks = document.querySelectorAll('.nav-link[href]:not([href="#"])');
                menuLinks.forEach(link => {
                    // 检查链接是否指向当前站点且不是退出链接
                    if (link.hostname === window.location.hostname && !link.href.includes('/accounts/logout/')) {
                        link.addEventListener('click', function(e) {
                            // 获取目标URL
                            const url = this.href;
                            
                            // 阻止默认的页面跳转
                            e.preventDefault();
                            
                            // 更新浏览器历史记录
                            history.pushState(null, '', url);
                            
                            // 加载内容到主区域
                            loadContent(url, this);
                            
                            // 更新活动状态，但不改变其他菜单的展开/折叠状态
                            updateActiveLinkOnly(this);
                        });
                    }
                });
            }
            
            // 仅更新活动链接函数（不改变其他菜单的展开/折叠状态）
            function updateActiveLinkOnly(activeLink) {
                // 移除所有活动状态
                document.querySelectorAll('.nav-link').forEach(link => {
                    link.classList.remove('active');
                });
                
                // 为当前链接添加活动状态
                activeLink.classList.add('active');
            }
            
            // Ajax加载内容函数
            function loadContent(url, clickedLink = null) {
                // 添加加载状态指示器
                const contentWrapper = document.querySelector('.content-wrapper');
                
                // 显示加载状态
                contentWrapper.innerHTML = `
                    <div class="d-flex justify-content-center align-items-center" style="height: 200px;">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                `;
                
                fetch(url, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.text())
                .then(html => {
                    // 创建临时元素来解析返回的HTML
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    // 只更新内容区域，不更新侧边栏
                    const newContent = doc.querySelector('.content-wrapper');
                    if (newContent) {
                        contentWrapper.innerHTML = newContent.innerHTML;
                    } else {
                        // 如果没有找到.content-wrapper，则使用整个返回的内容
                        contentWrapper.innerHTML = html;
                    }
                    
                    // 页面加载完成后，更新活动链接状态
                    if (clickedLink) {
                        // 移除所有活动状态
                        document.querySelectorAll('.nav-link').forEach(link => {
                            link.classList.remove('active');
                        });
                        
                        // 为当前链接添加活动状态
                        clickedLink.classList.add('active');
                    }
                })
                .catch(error => {
                    console.error('Error loading content:', error);
                    // 显示错误信息
                    contentWrapper.innerHTML = `
                        <div class="alert alert-danger" role="alert">
                            <h4 class="alert-heading">加载失败</h4>
                            <p>无法加载内容，请稍后重试。</p>
                        </div>
                    `;
                });
            }
        });
    </script>
    {% block extra_js %}{% endblock %}
</body>
</html>